import { INITIALIZE_CONDITION_URL_SYMBOL } from '../actions/fixup-work/conditionAction';

import { sendTopInfo, ENUM_INFO_TYPE } from '../actions/topAction';

// 请求成功的标识
const SUCCESS_CODE = 99999;

/**
 * 柯里化后的中间件形态, 用于发起存在异步请求的Action
 * @param  {Object} store [description]
 * @param  {Object} next [description]
 * @param  {Object} action [description]
 */
export const conditionAPICallerMiddleware = (store) => (next) => (action) => {
	let url = undefined;
	if (action.payload)
		url = action.payload[INITIALIZE_CONDITION_URL_SYMBOL];

	if (!url) {
		// 如果没有url在action中, 则直接跳到下一个可能存在的中间件中
		return next(action);
	};

	let { type, payload } = action;
	let { key } = payload;
	let [ REQUEST, SUCCESS, FAILURE ] = type;

	// 准备发起数据请求
	next({type: REQUEST, payload});

	if (__DEV__)
		console.log(`fetch target is ${url}`);

	// 请求数据
	return fetch(url)
		.then((res) => {
			// 将数据转为json
			return res.json();
		})
		.then((json) => {
			// TODO: 数据处理
			let action;

			if (json.code === SUCCESS_CODE) {
				action = { type: SUCCESS, payload: { data: json.data, key } };
			} else {
				action = { type: FAILURE, payload: { error: json.error } };

				// 创建一个顶层消息Action, 并发送出去
				let topAction = sendTopInfo(json.error, ENUM_INFO_TYPE.ERROR);
				next(topAction);
			}

			next(action);
		})
		.catch((error) => {
			// 发起的请求失败了
			next({ type: FAILURE });
			// 创建一个顶层消息Action, 并发送出去
			let topAction = sendTopInfo(error.message, ENUM_INFO_TYPE.ERROR);
			next(topAction);
		});
};